package org.dfl.core.data.types;

/**
 * simple type that can be merged only with the same type
 * @author Piotr Wlodarczyk
 *
 */
public class SimpleType extends Type {
	private static final String SIMPLE_ANY_TYPE = "?b";
	/** the name of this type */
	private String typeStr; 

	public SimpleType(String type) {
		super();
		setTypeStr(type);
	}
	
	protected String getTypeStr() {
		return typeStr;
	}

	@Override
	public boolean canMerge(Type t) {
		return ((t instanceof SimpleType && 
					(
							(((SimpleType)t).getTypeStr()==null)
							|| 
							(getTypeStr()==null)
							||
							((SimpleType)t).getTypeStr().equals(getTypeStr()))
					)
				||
				(t instanceof AnyType));
	}
	
	@Override
	protected boolean complain(Type t) {
		if(t == this) return true;
		if(t instanceof SimpleType){
			SimpleType tt = (SimpleType) t;
			if(getTypeStr()==null){
				setTypeStr(tt.getTypeStr());
				mergeParentsWith(t);
				return true;
			}else if(tt.getTypeStr()==null){
				return tt.complain(this);
			}else if(((SimpleType)t).getTypeStr().equals(getTypeStr())){
				mergeParentsWith(t);
				return true;
			}else{
				return false;
			}
		}else if(t instanceof AnyType){
			return t.complain(this);
		}else{
			return false;
		}
	}

	@Override
	public Type getCopy() {
		return new SimpleType(getTypeStr());
	}

	@Override
	public String save() {
		return getTypeStr()==null?SIMPLE_ANY_TYPE:getTypeStr();
	}

	protected void setTypeStr(String typeStr) {
		if(SIMPLE_ANY_TYPE.equals(typeStr)){
			this.typeStr = null;
		}else{
			this.typeStr = typeStr;
		}
	}
}
